<?php
/**
 * Created by PhpStorm.
 * User: zlkmu
 * Date: 2018/1/31
 * Time: 10:36
 */
use \GatewayWorker\Lib\Db;
require_once __DIR__.'/../Module/User.php';
class Player
{
    //玩家的openid
    public $userOpenId;
    //玩家的ID，在数据库中的唯一标记
    public $userUid;
    //玩家的昵称
    public $userNickname;
    //玩家的性别
    public $userSex;
    //玩家的头像
    public $userHeadImg;
    //玩家钻石
    public $userDiamond;
    //玩家房卡
    public $roomCard;
    //注册时间
    public $registerTime;
    //玩家地址
    public $playerAddress = "";
    //是否实名制
    public $realName;
    //玩家分享了多少次
    public $shareNum = 0;
    //玩家经纬度
    public $longitude;
    public $latitude;
    //玩家绑定的推广账号
    public $invitor;

    /**
     * 初始化普通用户信息(来自前台微信登录数据)
     * @param $playerInfo 微信登录传来的数据
     */
    private function initPlayerInfo($playerInfo)
    {
        echo "initPlayerInfo-------------------------";
        print_r($playerInfo);
        $this->userOpenId = $playerInfo["openId"];
        $this->userNickname = $playerInfo["nickName"];
        $this->userSex = $playerInfo["sex"];
        $this->userHeadImg = $playerInfo["headIcon"];

        //调用百度API获取到用户的详细地址

        $this->longitude = $playerInfo["longitude"];
        $this->latitude = $playerInfo["latitude"];
        $res = $this->getBaiDuAddress($this->longitude, $this->latitude);
        if ($res["status"] == 0) {
            $this->playerAddress = $res["result"]["formatted_address"];//设置具体的地理位置
        } else {
            $this->playerAddress = "获取地址失败！";
        }
    }

    /**
     * Player constructor.
     * @param $playerInfo 玩家信息，由前台微信登录传入
     * @param $isVisitor: false：普通登录 true：游客登录
     */
    function __construct($playerInfo, $isVisitor = false)
    {
        if (!$isVisitor) {
            //初始化玩家信息
            $this->initPlayerInfo($playerInfo);
            //检查数据库里面是否有该玩家的信息，如果没有，创建本记录
            $this->createUserToDB();
        } else  {
            //游客登录
            $this->createVisitorsUserToDB($playerInfo);
        }
    }

    /**
     * 获取百度地图的位置信息
     * @param $x
     * @param $y
     * @return mixed
     */
    private function getBaiDuAddress($x, $y)
    {
        //初始化
        $curl = curl_init();
        //设置抓取的url//pois=1&
        curl_setopt($curl, CURLOPT_URL, "http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&coordtype=wgs84ll&location=$y,$x&output=json&pois=1&ak=d0BPB4lIQpwhois8NMgB5OhzI6pNa08Z");
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);

        preg_match("/renderReverse&&renderReverse\\((.*)\\)/", $data, $r);

        return json_decode($r[1], true);
    }

    /**
     * 获取玩家UID
     * @return mixed
     */
    public function getUserID()
    {
        return $this->userUid;
    }

    /**
     * 设置玩家UID
     * @param $userUid
     */
    public function setUserID($userUid)
    {
        $this->userUid = $userUid;
    }

    /**
     * 将玩家注册入数据库的函数
     */
    private function registerUserTODB()
    {
        $db = Db::instance('game');
        $resId = $db->insert('qg_user')->cols(array(
            'user_openid' => $this->userOpenId,
            'user_nickname' => $this->userNickname,
            'user_sex' => $this->userSex,
            'user_diamond' => 0,
            'room_card' => 38,
            'user_headimg' => $this->userHeadImg,
            'register_time' => date("Y-m-d H:i:s"),
        ))->query();
        //设置当前用户UID
        $this->userUid = (int)$resId;
        $this->userDiamond = 0;
        $this->roomCard = 38;
        $this->registerTime = date("Y-m-d H:i:s");
        $this->realName = false;
        $this->shareNum = 0;
    }

    /**
     * 从数据库信息中更新玩家信息，并更新数据库中玩家相关微信信息的函数
     * @param $userDBResult 从数据库中得到的玩家信息结果
     */
    private function updateUserToDB($userDBResult)
    {
        $db = Db::instance('game');
        //已经注册 设置当前用户UID(并更新微信上的数据到数据库)
        $this->userUid = (int)$userDBResult[0]["user_uid"];
        $this->userDiamond = (int)$userDBResult[0]["user_diamond"];
        $this->roomCard = (int)$userDBResult[0]["room_card"];
        $this->registerTime = $userDBResult[0]["register_time"];
        if ($userDBResult[0]["is_certification"] == 1) {
            $this->realName = false;
        } else if ($userDBResult[0]["is_certification"] == 2) {
            $this->realName = true;
        }

        $db->update('qg_user')->cols(array(
            'user_nickname' => $this->userNickname,
            'user_sex' => $this->userSex,
            'user_headimg' => $this->userHeadImg,
        ))->where("user_openid=:id")->bindValues(array('id' => $this->userOpenId))->query();

        $u = new User();
        $this->shareNum = $u->checkShare($this->userUid);
    }

    //创建游戏玩家（检查是否已注册、否则注册）
    function createUserToDB()
    {
        $db = Db::instance('game');
        $s = $db->select('user_openid,user_uid,user_nickname,user_sex,user_headimg,user_diamond,room_card,register_time,is_certification')
            ->from('qg_user')->where("user_openid=:id")->bindValues(array('id' => $this->userOpenId))->query();
        if (!$s) {
            //代表着此玩家没有注册，所以需要注册
            $this->registerUserTODB();
        } else {
            //否则，根据数据库信息初始化玩家基本信息，并更新玩家和微信相关的信息
            $this->updateUserToDB($s);
        }
    }

    //创建游戏玩家（检查是否已注册、否则注册）游客玩家
    function createVisitorsUserToDB($userUid)
    {
        $db = Db::instance('game');

        //当用户传了UID
        if ($userUid) {
            $s = $db->select('user_openid,user_uid,user_nickname,user_sex,user_headimg,user_diamond,room_card,register_time,is_certification')
                ->from('qg_user')->where("user_uid=:id")->bindValues(array('id' => $userUid))->query();
            if (!$s) {
                //代表着此玩家没有注册，所以需要注册
                $resId = $db->insert('qg_user')->cols(array(
                    'user_openid' => sha1(date("Y-m-d H:i:s") . mt_rand(100, 900)),
                    'user_nickname' => "游客" . mt_rand(100, 999),
                    'user_sex' => 1,
                    'user_diamond' => 0,
                    'room_card' => 38,
                    'user_headimg' => "http://www.dounius.com/Uploads/tou.jpg",
                    'register_time' => date("Y-m-d H:i:s"),
                ))->query();
                //设置当前用户UID
                $this->userUid = (int)$resId;

                $s = $db->select('user_openid,user_uid,user_nickname,user_sex,user_headimg,user_diamond,room_card,register_time,is_certifiaction')
                    ->from('qg_user')->where("user_uid=:id")->bindValues(array('id' => $this->userUid))->query();
                $this->userDiamond = (int)$s[0]["user_diamond"];
                $this->roomCard = (int)$s[0]["room_card"];
                $this->registerTime = $s[0]["register_time"];
                $this->userOpenId = $s[0]["user_openid"];
                $this->userNickname = $s[0]["user_nickname"];
                $this->userSex = $s[0]["user_sex"];
                $this->userHeadImg = $s[0]["user_headimg"];
                if ($s[0]["is_certification"] == 1) {
                    $this->realName = false;
                } else if ($s[0]["is_certification"] == 2) {
                    $this->realName = true;
                }
            } else {
                //已经注册 设置当前用户UID(并更新微信上的数据到数据库)
                $this->userUid = (int)$s[0]["user_uid"];
                $this->userDiamond = (int)$s[0]["user_diamond"];
                $this->roomCard = (int)$s[0]["room_card"];
                $this->registerTime = $s[0]["register_time"];
                if ($s[0]["is_certification"] == 1) {
                    $this->realName = false;
                } else if ($s[0]["is_certification"] == 2) {
                    $this->realName = true;
                }
            }
        } else {
            //用户没有传UID
            //代表着此玩家没有注册，所以需要注册
            $resId = $db->insert('qg_user')->cols(array(
                'user_openid' => sha1(date("Y-m-d H:i:s") . mt_rand(100, 900)),
                'user_nickname' => "游客" . mt_rand(100, 999),
                'user_sex' => 1,
                'user_diamond' => 0,
                'room_card' => 38,
                'user_headimg' => "http://www.dounius.com/Uploads/tou.jpg",
                'register_time' => date("Y-m-d H:i:s"),
            ))->query();
            //设置当前用户UID
            $this->userUid = (int)$resId;

            $s = $db->select('user_openid,user_uid,user_nickname,user_sex,user_headimg,user_diamond,room_card,register_time,is_certifiaction')
                ->from('qg_user')->where("user_uid=:id")->bindValues(array('id' => $this->userUid))->query();
            $this->userDiamond = (int)$s[0]["user_diamond"];
            $this->roomCard = (int)$s[0]["room_card"];
            $this->registerTime = $s[0]["register_time"];
            $this->userOpenId = $s[0]["user_openid"];
            $this->userNickname = $s[0]["user_nickname"];
            $this->userSex = $s[0]["user_sex"];
            $this->userHeadImg = $s[0]["user_headimg"];
            if ($s[0]["is_certification"] == 1) {
                $this->realName = false;
            } else if ($s[0]["is_certification"] == 2) {
                $this->realName = true;
            }
        }

    }


}



?>